import React, { useEffect, useState, useRef } from "react";
import { Switch, Table, Button, Modal } from "antd";
import UserForm from "../../../components/user-manage/UserForm.js";
import axios from "axios";
import {
  DeleteOutlined,
  EditOutlined,
  ExclamationCircleOutlined,
} from "@ant-design/icons";

const { confirm } = Modal;
export default function UserList() {
  //Data
  const [dataSource, setdataSource] = useState([]);
  const [isAddVisible, setIsAddVisible] = useState(false); //控制添加用户模态框
  const [roleList, setRoleList] = useState([]);
  const [regionList, setRegion] = useState([]);
  const [isUpdateVisible, setIsUpdateVisible] = useState(false); //控制编辑表单模态框
  const [current, setCurrent] = useState(null);
  const addForm = useRef(null);
  const updateForm = useRef(null);
  const [isUpdateDisable, setIsUpdateDisable] = useState(false);
  const columns = [
    {
      title: "地域",
      dataIndex: "region",
      filters: [
        ...regionList.map((item) => ({
          text: item.title,
          value: item.value,
        })),
        {
          text: "全球",
          value: "全球",
        },
      ],
      render: (region) => {
        return <strong>{region === "" ? "全球" : region}</strong>;
      },
      onFilter: (value, item) => {
        if (value === "全球") {
          return item.region === "";
        }
        return item.region === value;
      },
    },
    {
      title: "角色名称",
      dataIndex: "role",
      render: (role) => {
        return role?.roleName;
      },
    },
    {
      title: "用户名",
      dataIndex: "username",
    },
    {
      title: "用户状态",
      dataIndex: "roleState",
      render: (roleState, item) => {
        return (
          <Switch
            checked={roleState}
            disabled={item.default}
            onChange={() => {
              handleChange(item);
            }}
          ></Switch>
        );
      },
    },
    {
      title: "操作",
      render: (item) => {
        return (
          <div>
            {/* 删除用户 */}
            <Button
              danger
              shape="circle"
              icon={<DeleteOutlined />}
              style={{ marginRight: "5px" }}
              onClick={() => {
                confirmMethod(item);
              }}
            />
            {/* 编辑用户信息 */}
            <Button
              type="primary"
              shape="circle"
              icon={<EditOutlined />}
              onClick={() => {
                handleUpdate(item);
              }}
            />
          </div>
        );
      },
    },
  ];

  //Methods
  //是否删除的对话框
  const confirmMethod = (item) => {
    confirm({
      title: "你确定要删除吗?",
      icon: <ExclamationCircleOutlined />,
      onOk() {
        deleteMethod(item);
      },
      onCancel() {
        console.log("取消");
      },
    });
  };
  //点击确认删除后的方法
  const deleteMethod = (item) => {
    if (item.grade === 1) {
      // 当前页面同步状态+后端更新
      setdataSource(
        dataSource.filter((data) => {
          return data.id !== item.id;
        })
      );
    } else {
      let list = dataSource.filter((data) => {
        return data.id === item.rightId;
      });
      list[0].children = list[0].children.filter((data) => {
        return data.id !== item.id;
      });
      setdataSource([...dataSource]);
    }
  };
  //点击确认后的回调
  const addFormOk = () => {
    addForm.current
      .validateFields()
      .then((value) => {
        setIsAddVisible(false);
        //重置表单
        addForm.current.resetFiledValue();
        //post到后端生成ID，再设置datasource，方面后面的删除和更新处理
        axios
          .post(`/users`, {
            ...value,
            roleState: true,
            default: false,
          })
          .then((res) => {
            console.log(res.data, "新数据");
            setdataSource([
              ...dataSource,
              {
                ...res.data,
                role: roleList.filter((item) => item.id === value.roleId)[0],
              },
            ]);
          });
      })
      .catch((err) => {
        console.log(err);
      });
  };
  //点击用户状态按钮的回调
  const handleChange = (item) => {
    item.roleState = !item.roleState;
    setdataSource([...dataSource]);
    axios.patch(`/users/${item.id}`, {
      roleState: item.roleState,
    });
  };
  //点击编辑按钮的回调
  const handleUpdate = (item) => {
    //放在异步中，确保同步更新
    setTimeout(() => {
      setIsUpdateVisible(true);
      if (item.roleId === 1) {
        //禁用
        setIsUpdateDisable(true);
      } else {
        //取消禁用
        setIsUpdateDisable(false);
      }
      updateForm.current.setFieldsValue(item);
    });

    setCurrent(item);
  };
  //点击编辑里更新按钮的回调
  const updateFormOk = () => {
    updateForm.current.validateFields().then((value) => {
      setIsUpdateVisible(false);
      setdataSource(
        dataSource.map((item) => {
          if (item.id === current.id) {
            return {
              ...item,
              ...value,
              role: roleList.filter((data) => data.id === value.roleId)[0],
            };
          }
          return item;
        })
      );
      setIsUpdateDisable(!isUpdateDisable);
      axios.patch(`/users/${current.id}`, value);
    });
  };
  const { roleId, region, username } = JSON.parse(
    localStorage.getItem("token")
  );

  //useEffect
  useEffect(() => {
    const roleObj = {
      1: "superadmin",
      2: "admin",
      3: "editor",
    };
    axios.get("/users?_expand=role").then((res) => {
      const list = res.data;
      setdataSource(
        roleObj[roleId] === "superadmin"
          ? list
          : [
              ...list.filter((item) => item.username === username),
              ...list.filter(
                (item) =>
                  item.region === region && roleObj[item.roleId] === "editor"
              ),
            ]
      );
    });
  }, [roleId, region, username]);
  useEffect(() => {
    axios.get("/regions").then((res) => {
      setRegion(res.data);
    });
  }, []);
  useEffect(() => {
    axios.get("/roles").then((res) => {
      setRoleList(res.data);
    });
  }, []);

  return (
    <div>
      <Button
        type="primary"
        onClick={() => {
          setIsAddVisible(true);
        }}
      >
        添加
      </Button>
      <Table
        dataSource={dataSource}
        columns={columns}
        rowKey={(item) => item.id}
      ></Table>
      {/* 添加新用户的模态框 */}
      <Modal
        visible={isAddVisible}
        title="添加用户"
        okText="确定"
        cancelText="取消"
        onCancel={() => {
          setIsAddVisible(false);
        }}
        onOk={() => addFormOk()}
      >
        <UserForm
          regionList={regionList}
          roleList={roleList}
          ref={addForm}
        ></UserForm>
      </Modal>

      {/* 更新的模态框 */}
      <Modal
        visible={isUpdateVisible}
        title="更新用户"
        okText="更新"
        cancelText="取消"
        onCancel={() => {
          setIsUpdateVisible(false);
          setIsUpdateDisable(!isUpdateDisable);
        }}
        onOk={() => updateFormOk()}
      >
        <UserForm
          regionList={regionList}
          roleList={roleList}
          ref={updateForm}
          isUpdateDisable={isUpdateDisable}
          isUpdate={true}
        ></UserForm>
      </Modal>
    </div>
  );
}
